<!--
 * @页面名称:
 * @描述: 左边tree数据
 * @作者: 
 * @Date:
 -->
<template>
  <div class="leftTree">
    <el-button type="primary" style="width: 100%" @click="toggle">{{ name }}</el-button>
    <!-- 搜索栏 -->
    <el-input v-model="searchVal" placeholder="请输入想要搜索的内容" enter-button @change="onSearch" />
    <ztree
      class="tree"
      :setting="treeSetting.setting"
      :nodes="treeSetting.treeData"
      @onClick="onClick"
      @onCreated="handleCreated"
    >
    </ztree>
    <el-button @click="noClassManage" :class="{ active: btnStatus }"> 无分类管理 </el-button>
    <el-button v-if="isShowRecycle" style="margin-left: 0" @click="recycle" :class="{ active2: btnStatus2 }"> 回收站 </el-button>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch, computed } from "vue";
import Ztree from "@/components/Ztree/Ztree.vue";
import { useCatalogStore } from "@/stores/modules/catalog";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useRoute } from "vue-router";
import { ButtonStatus } from "../../components/TopBar/InitButton";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { cloneDeep } from "lodash-es";
import { getSysConfig } from "@/utils/util";

const emit = defineEmits(["onClick", "noClassManage", "recycle"]);
const buttonStatus = new ButtonStatus();
const catalogStore = useCatalogStore();
const { proxy } = useCurrentInstance();
const dynamicStore = useDynamicStore();
const route = useRoute();
// 搜索条件
const searchVal = ref("");
// tree配置
const treeSetting = reactive({
  setting: {
    // ztree配置
    data: {
      simpleData: {
        enable: true,
        idKey: "Catalog_ID",
        pIdKey: "Catalog_Father"
      },
      key: {
        name: "Catalog_Name"
      }
    },
    view: {
      showIcon: false
    }
  },
  treeData: [] as any[],
  ztreeObj: {} as any
});
// 归档范围名字
const name = ref("档案分类");
// 归档范围名字集合
const typeList = ref(["档案分类", "归档范围"]);
// 分类切换当前下标
const currentIndex = ref(0);
// 是否归档范围
const isFilingScope = ref(false);
// 归档范围按钮状态
const btnStatus = ref(false);
// 回收站按钮状态
const btnStatus2 = ref(false);
// 是否显示回收站
const isShowRecycle = computed(() => {
  const isShow = getSysConfig("isShowRecycle");
  const isRecycle = catalogStore.catalogList.filter((v: any) => v.Catalog_Code === "Recycle")[0];
  if (isShow && isShow.toLowerCase() === "true" && isRecycle) {
    return true;
  } else {
    return false;
  }
});
// 初始化树对象
let ztreeObj = reactive({});

// 获取树数据
const getTreeData = async () => {
  if (route.query) {
    await proxy.$vueAxios
      .get(
        "MasterPermission/GetUserPermissionCatalog",
        {
          fmtId: route.query.fmtid,
          status: route.query.status,
          isFilingScope: isFilingScope.value
        },
        {
          noLoading: true
        }
      )
      .then((res: any) => {
        const result: any[] = [];
        res.List.filter((v: any) => v.Is_UnCatalog !== true && v.Catalog_Code !== "Recycle").forEach((item: any) => {
          result.push({ ...item, Catalog_Name: `${item.Catalog_Code} ${item.Catalog_Name}`, open: item.Catalog_Enable_Expand });
        });
        treeSetting.treeData = result;
        catalogStore.setCatalogList(res.List);
        catalogStore.setSourthCatalogList(cloneDeep(res.List));
      });
  } else {
    proxy.$message.warning("请选择全宗节点!!!");
  }
};
// 点击树节点
const onClick = (treeNode: any) => {
  catalogStore.SetTreeNode(treeNode);
  const isCanLoad = getSysConfig("parentNodeCanLoad");
  console.log(isCanLoad, treeNode);
  if (isCanLoad == "1" && treeNode?.children) {
    proxy.$message.warning("非叶子节点,不可加载数据!");
    return;
  }
  btnStatus.value = false;
  btnStatus2.value = false;
  dynamicStore.setNoCatalog(false);
  buttonStatus.filterButtonAuth(JSON.parse(treeNode.PC_PermissionStr)[0]);
  emit("onClick", treeNode);
};
// 初始化树
const handleCreated = (obj: any) => {
  ztreeObj = obj;
};
// 搜索事件
const onSearch = () => {
  if (searchVal.value) {
    const nodes = ztreeObj.getNodesByParamFuzzy("Catalog_Name", searchVal.value, null);
    treeSetting.treeData = nodes;
  } else {
    getTreeData();
  }
};
// 无分类管理
const noClassManage = () => {
  const treeNode = catalogStore.catalogList.filter((v: any) => v.Is_UnCatalog === true)[0];
  if (treeNode) {
    buttonStatus.filterButtonAuth(JSON.parse(treeNode?.PC_PermissionStr)[0]);
  } else {
    buttonStatus.filterButtonAuth([]);
  }
  ztreeObj.cancelSelectedNode();
  catalogStore.SetTreeNode(treeNode);
  btnStatus.value = true;
  btnStatus2.value = false;
  dynamicStore.setNoCatalog(true);
  emit("noClassManage");
};
// 切换归档范围
const toggle = () => {
  isFilingScope.value = !isFilingScope.value;
  currentIndex.value = currentIndex.value + 1;
  if (currentIndex.value >= 2) {
    // 如果超出maxLength,currentIndex置为0
    currentIndex.value = 0;
  }
  if (currentIndex.value < 2) {
    name.value = typeList.value[currentIndex.value];
  }
  getTreeData();
};
// 回收站按钮点击事件
const recycle = () => {
  buttonStatus.filterButtonAuth([]);
  ztreeObj.cancelSelectedNode();
  catalogStore.SetTreeNode({});
  btnStatus.value = false;
  btnStatus2.value = true;
  emit("recycle");
};
// 清楚树节点选中状态
const clearTreeNodeSelect = () => {
  ztreeObj.cancelSelectedNode();
};
defineExpose({ onClick, getTreeData, clearTreeNodeSelect });
onMounted(() => {
  getTreeData();
});
// 监听fmtid
watch(
  () => route.query,
  (newVal, oldVal) => {
    if (route.fullPath.includes("/dynamicMain")) {
      proxy.$vueAxios
        .get(
          "MasterPermission/GetUserPermissionCatalog",
          {
            fmtId: newVal.fmtid,
            status: newVal.status
          },
          {
            noLoading: true
          }
        )
        .then((res: any) => {
          const result: any[] = [];
          res.List.forEach((item: any) => {
            result.push({ ...item, Catalog_Name: `${item.Catalog_Code} ${item.Catalog_Name}`, open: item.Catalog_Enable_Expand });
          });
          catalogStore.setCatalogList(res.List);
        });
    }
  }
);
</script>

<style scoped lang="scss">
.el-tabs {
  // height: 100%;
  :deep(.el-tabs__header) {
    margin: 0;
  }
  :deep(.el-tabs__item) {
    padding: 0;
  }
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  font-size: 32px;
  font-weight: 600;
  color: #6b778c;
}
.demo-tabs .custom-tabs-label .el-icon {
  vertical-align: middle;
}
.demo-tabs .custom-tabs-label span {
  margin-left: 4px;
  vertical-align: middle;
}
.active,
.active2 {
  color: var(--el-button-active-text-color);
  background-color: var(--el-button-active-bg-color);
  border-color: var(--el-button-active-border-color);
}
.leftTree {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 5px;
  height: 100%;
  padding: 5px 8px;
  .tree {
    flex: 1;
  }
}
</style>
